package com.bins.knowledge.point.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {

    private final int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // 处理连接请求的线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理具体任务的线程组
        try {
            ServerBootstrap b = new ServerBootstrap(); // 引导类，用于设置服务器的各种参数
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // 使用NIO的通道实现
             .localAddress(port) // 设置端口号
             .childHandler(new ChannelInitializer<SocketChannel>() { // 设置具体的处理类
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new StringDecoder()); // 解码器，将ByteBuf转换为String
                     ch.pipeline().addLast(new StringEncoder()); // 编码器，将String转换为ByteBuf
                     ch.pipeline().addLast(new SimpleServerHandler()); // 自定义的处理器
                 }
             });
            ChannelFuture f = b.bind().sync(); // 绑定端口并开始接收进来的连接
            f.channel().closeFuture().sync(); // 等待直到服务器socket关闭
        } finally {
            bossGroup.shutdownGracefully(); // 优雅地关闭线程组和释放所有资源
            workerGroup.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws Exception {
        new NettyServer(8080).run(); // 启动服务器，监听8080端口
    }
}
